# -*- coding: utf-8 -*-
import sys
sys.path.append("../..")
from db.mysql import MysqlClient
from itertools import product
from common.helper import Helper
from common.config import *
import json
import aiohttp, asyncio


class Spider(object):
    def __init__(self):
        self.mysql = MysqlClient()
        self.name = "百万安行保返还型意外险"

    def genProductInfo(self):
        plan = {

            "year": [str(i) for i in range(18, 55)],
            "gender": ["M", "F"],
            "days": ["30y", "20y"],
            "interval": ["10"],
            "people_count": ["1", "2"],
            "airplane_death": ["5000000"],
            "private_death": ["1000000"],
            "common_traffic": ["1000000"],
            "accident_death": ["200000"],

        }

        for v in product(plan["year"], plan["gender"], plan["days"], plan["interval"], plan["people_count"],
                         plan["airplane_death"],
                         plan["private_death"], plan["common_traffic"], plan["accident_death"]):
            data = Helper.formatProductInfo(plan, v)
            yield data

    # 异步爬虫
    async def requestJson(self, dt):
        params = self.filterPayload(dt)
        payload = json.dumps(params)
        async with aiohttp.ClientSession() as session:
            async with session.post(url=domain[self.name]["url"], headers=domain[self.name]["header"],
                                    data=payload) as resp:
                res = await resp.text()
                if "该年龄不在购买范围内" in res:
                    pass
                else:
                    data = {
                        "name": self.name,
                        "company": "国华人寿",
                        "price": json.loads(res)["content"]["resultPrice"] if dt[
                                                                                  "people_count"] == "1" else Helper.decimalParse(
                            float(json.loads(res)["content"]["resultPrice"]) * 2)
                    }
                    data.update( dt )
                    Helper.mergeTable(self.name,self.mysql,data)

    # filterPayload
    def filterPayload(self, data=None):
        params = {"productCode": "1052" if data["days"] == "20y" else "1051",
                  "productName": "" + data["days"].replace("y", "") + "年", "salePlanCode": "GHGW_1010",
                  "sex": "1" if data["gender"] == "F" else "0",
                  "birthDate": "" + str(2020 - int(data["year"])) + "-01-01", "type": "web", "system": "gh"}
        return params

    def asyncTask(self):
        tasks = [self.requestJson(data) for data in self.genProductInfo()]
        event_loop = asyncio.get_event_loop()
        event_loop.run_until_complete(asyncio.gather(*tasks))
        event_loop.close()
